<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\Exception;
use think\facade\Cache;
use think\facade\Event;
use app\common\controller\Config;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,level_id,team_id,team_total,my_total');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,level_id,team_id,team_total,my_total');
    }

    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
    {
        try {
            parent::create([
                'uid'      => $parentId,
                'code'     => $parentCode,
                'algebra'  => 1,
                'new_uid'  => $new_uid,
                'new_code' => $new_code,
            ]);
            $time = time();

            parent::where('new_uid', $parentId)
                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,"' . $new_code . '" as new_code')
                ->selectInsert([
                    'uid',
                    'code',
                    'algebra',
                    'create_time',
                    'update_time',
                    'new_uid',
                    'new_code',
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }
    /**
     * 推荐奖
     */
    public static function tpMoney($money, $user,$accountkey)
    {
        $sys = Config::lists();
        try {
            $tp_money = 0;
            if ($user->parent_id != 0) {
                $tuser = User::where('id',$user->parent_id)->find();
                /**
                 * 间推奖
                 */
                if ($tuser->parent_id != 0) {
                    $tpuser = User::where('id',$tuser->parent_id)->find();
                    if(!empty($tpuser)){
                        $tp_money = round($money * $sys['tp_2'], 2);
                        Target::Account()->basics($tuser->parent_id, $accountkey, $tp_money, '间推奖励', '+')
                            ->createBonus($user->id, 6);
                    }
                }
            }
            if ($tp_money > 0) {
                //统计收入，则需使用
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $tp_money]);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 积分商城团队奖
     */
    public static function teamMoney($money, $user)
    {

        $sys = Config::lists();
        try {
            $tp_money = 0;
            /**推荐奖 */
            if ($user->parent_id != 0) {
                $tp_money = round($money * $sys['tp_1'], 2);
                Target::Account()->basics($user->parent_id, 'currency', $tp_money , '直推奖励', '+')
                    ->createBonus($user->id, 1);
            }
            $level = 1;
            $list = parent::with('user')->where('new_uid', $user->id)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            $money_toal = 0;
            foreach ($list as $k => $v) {
                if ($v->user->team_id >= $level) {
                    $team = TeamLevel::where('id', $v->user->team_id)->find();
                    if (!empty($team)) {
                        $toal = round($team['integral'] * $money, 2);
                        $money_toal += $toal;
                        Target::Account()->basics($v->uid, 'currency', $toal, $team->title . '积分星级服务', '+')
                            ->createBonus($user->id, 2);
                        $level = $v->user->team_id + 1;
                    }
                }
            }
            if ($money_toal > 0) {
                //统计收入，则需使用
                Event::trigger('Statistics', ['key' => 'expend', 'value' => ($money_toal + $tp_money)]);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 抢红包发奖
     */
    public static function packetMoney($money, $user)
    {
        try {
            $level = $user->team_id + 1;
            $list = parent::with('user')->where('new_uid', $user->id)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            $money_toal = 0;
            foreach ($list as $k => $v) {
                if ($v->user->team_id == $level) {
                    $team = TeamLevel::where('id', $level)->find();
                    if (!empty($team)) {
                        $toal = round($team['packet'] * $money, 2);
                        $money_toal += $toal;
                        Target::Account()->basics($v->uid, 'bonus', $toal, $team->title . '抢红包提成', '+')
                            ->createBonus($user->id, 3);
                        $level += 1;
                    }
                }
            }
            if ($money_toal > 0) {
                //统计收入，则需使用
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $money_toal]);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            // $userlist = [];
            foreach ($list as $item) {
                $min_total = ($item->user->my_total + $item->user->team_total) / 10000;
                $team_uid = parent::where('uid', $item->uid)->where('algebra', 1)->column('new_uid');
                $count = User::whereIn('id', $team_uid)->where('level_id', 2)->count();
                $level = TeamLevel::where('id', '>', $item->user->team_id)
                    ->where('team_money', '<=', $min_total)
                    ->where('zt_count', '<=', $count)
                    ->order('id', 'desc')
                    ->find();
                // $userlist[]=$level;
                if ($level) {
                    User::update(['team_id' => $level->id, 'id' => $item->user->id]);
                }
            }
            // print('<pre>');print_r($userlist);die;
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 金币商城奖金
     */
    public static function teamGoldMoney($info, $user)
    {
        $sys = Config::lists();
        $money = $info->real_amount - $info->freight;
        $product_id = OrderProduct::where('order_id',$info->id)->value('pid');
        $product = Product::where('id',$product_id)->find();
        try {
            $tp_money = 0;
            $merchant_money = 0;
            $merchant_tp_money = 0;
            /**
             * 商家收入
             */
            $merchant_id = Merchant::where(['id' => $info->merchant_id, 'status' => 2])->value('uid');
            $merchantUser = User::where('id', $merchant_id)->find();
            if (!empty($merchantUser) && $merchantUser->is_merchant == 1) {
                $merchant_money = round($money * $product['merchant_bl'], 2);
                Target::Account()->basics($merchant_id, 'bonus', $merchant_money, '商家收入', '+')
                    ->createNormal($user->id);
            }
            /**
             * 商家推荐人
             */
            if ($merchantUser->parent_id != 0) {
                $merchant_tp_money = round($money * $product['tp_2'], 2);
                Target::Account()->basics($merchantUser->parent_id, 'bonus', $merchant_tp_money, '直推商家奖', '+')
                    ->createBonus($user->id, 1);
            }
            /**推荐奖 */
            if ($user->parent_id != 0) {
                $tp_money = round($money * $product['tp_1'], 2);
                Target::Account()->basics($user->parent_id, 'bonus', $tp_money, '直推消费奖', '+')
                    ->createBonus($user->id, 1);
            
            }
            $level = 1;
            $list = parent::with('user')->where('new_uid', $user->id)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            $money_toal = 0;
            foreach ($list as $k => $v) {
                if ($v->user->team_id >= $level) {
                    $team = TeamLevel::where('id', $v->user->team_id)->find();
                    if (!empty($team)) {
                        $toal = round($product['service_'.$team->id] * $money, 2);
                        $money_toal += $toal;
                        Target::Account()->basics($v->uid, 'bonus', $toal, $team->title . '金币星级服务', '+')
                            ->createBonus($user->id, 4);
                        $level = $v->user->team_id + 1;
                    }
                }
            }
            if ($money_toal > 0) {
                //统计收入，则需使用
                Event::trigger('Statistics', ['key' => 'expend', 'value' => ($money_toal + $tp_money + $merchant_money + $merchant_tp_money)]);
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
